<script>
import _ from 'lodash'
import Draggable from 'vuedraggable'
import store from '../../../../store/'
import FormItemDispatcher from '../dispatcher'
import emitter from '../../../../mixins/emitter.js'
import dataObjectConf from '../data-object-conf.js'
import { getUiItemExtraForEditable, getFormItemDataObject, generateOperateButtons } from '../mixins.js'

const getRowDataObject = context => {
  const { setting } = context.props
  const extra = getUiItemExtraForEditable(context)
  return _.merge({}, dataObjectConf, {
    props: {
      gutter: setting.options.gutter,
      align: setting.options.align,
      justify: setting.options.justify,
      type: 'flex'
    }
  }, extra)
}

const getColDataObject = (setting, index) => {
  return _.merge({}, dataObjectConf, {
    props: { span: setting.span },
    key: index
  })
}

const generateDragWidget = (h, context, item, index) => {
  const { setting } = context.props
  let list = _.cloneDeep(item.list)
  return h('Draggable', {
    'class': { 'zlst-col--placeholder': true },
    props: {
      options: { group: 'widgets', ghostClass: 'ghost' },
      list
    },
    on: {
      change () {
        const columns = setting.options.columns
        let columnsClone = _.cloneDeep(columns)
        columnsClone[index].list = list
        emitter.methods.dispatch(
          'MainBoard',
          'field-property-changed',
          [setting.id, 'columns', columnsClone],
          context
        )
      }
    }
  },
  generateColWidgets(h, context, item, true)
)}

const generateColWidgets = (h, context, item, editable = false) => {
  const { setting } = context.props
  let list = _.cloneDeep(item.list)
  return list.map(el => {
    return h('FormItemDispatcher', {
      key: el.id,
      props: {
        setting: el,
        editable,
        selected: el.id === store.getters['uiEditor/currentWidgetId']
      }
    })
  })
}

export default {
  props: [
    'setting',
    'editable',
    'selected'
  ],
  components: {
    Draggable,
    FormItemDispatcher
  },
  functional: true,
  render (h, context) {
    const { editable, setting } = context.props
    const extra = editable ? generateOperateButtons(h, context) : []
    return h('Row', getRowDataObject(context), [
      ...setting.options.columns.map((item, index) => {
        return h('Col', getColDataObject(item, index),
          editable ? [generateDragWidget(h, context, item, index)] : generateColWidgets(h, context, item)
        )
      }),
      ...extra
    ])
  }
}
</script>
